import React, { useEffect, useState, useRef } from 'react';
import { Table } from 'antd';

const App = (props) => {
  const { dataSource, rollTime = 60, rollNum = 5, rollTop = 1, flag = true } = props;
  const [timer, setTimer] = useState(); // 定时器
  const TableContainer = useRef();
  useEffect(() => {
    InitialScroll(dataSource);
    return () => {
      clearInterval(timer);
    };
  // eslint-disable-next-line
  }, [dataSource]); 

  // 开启定时器
  const InitialScroll = (data) => {
    clearInterval(timer)
    let container = TableContainer.current;
    container = container.getElementsByClassName('ant-table-body')[0];
    if (data.length > Number(rollNum) && flag) {
      // 只有当大于10条数据的时候 才会看起滚动
      let time = setInterval(() => {
        container.scrollTop += Number(rollTop);
        if (Math.ceil(container.scrollTop) >= Number(container.scrollHeight - container.clientHeight)) {
          container.scrollTop = 0;
          // setTimeout(() => { container.scrollTop = 0 }, 1000)
        }
      }, Number(rollTime));
      setTimer(time); // 定时器保存变量 利于停止
    }
  };
  return (
    <div 
      onMouseOver={() => clearInterval(timer)} 
      onMouseOut={() => InitialScroll(dataSource)}
    >
      <Table
        className='app-scroll-table' 
        ref={TableContainer}
        pagination={false}
        scroll={{
          y: 146,
          x: '100%',
          scrollToFirstRowOnChange: true,
        }}
        {...props}
      />
    </div>
  );
}

export default App;




// import React, { useEffect, useState, useRef } from 'react';

// const App = () => {

//   const someArrayToMap = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
//   const TableContainer = useRef();

//   console.log('TableContainer', TableContainer);

//   useEffect(() => {
//     info();
//   }, []);

//   const info = () => {
//     for (let i = 1; i <= 100; i++) {
//       setTimeout(() => (TableContainer.current.scrollTop = i), i * 2);
//     }
//   }

//   return (
//     <div>
//       <button onClick={() => info()}>CLICK TO SCROLL</button>
//       <div ref={TableContainer} style={{overflow: 'auto', height: '200px'}}>
//         {
//           [...someArrayToMap,
//           ...someArrayToMap,
//           ...someArrayToMap,
//           ...someArrayToMap,
//           ...someArrayToMap,
//           ...someArrayToMap,
//           ...someArrayToMap].map((e, i) => <div key={i}>some text here</div>)
//         }
//       </div>
//     </div>
//   )
// }


// export default App;


